package tools;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Slf4j(topic = "端口检测类")
public class CheckPortUtil {
    public static void checkPort(int port) {
        if("".equals(port)){
            log.error("端口未找到");
        } else {
            boolean flag = isPortAvailable(port);
            if(flag){
                log.info(port+"端口未被占用，请放心使用");
            }else{
                log.error(port+"端口已占用，请关闭或修改所占用端口");
            }
        }

    }
    /**
     * 查看端口是否被占用
     * @param port
     * @return
     */
    public static boolean  isPortAvailable(int port) {
        Socket s = new Socket();
        boolean flag=false;
        String f="";
        List<String> ipList=new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface nif = netInterfaces.nextElement();
                Enumeration<InetAddress> iparray = nif.getInetAddresses();
                while (iparray.hasMoreElements()) {
                    ipList.add(iparray.nextElement().getHostAddress());
                }
            }

            for (int i = 0; i < ipList.size(); i++) {
                flag=bindPort(ipList.get(i), port);
                if(!flag){
                    break;
                }
            }


        } catch (Exception e) {

            return false;
        }
        if(flag){//未被占用
            System.out.println("自定义端口可用");
            return true;
        }else{//已被占用
            System.out.println("自定义端口不可用");

            return false;
        }
    }

    /**
     * 查看是否能绑定ip端口
     * @param host
     * @param port
     * @return
     * @throws Exception
     */

    @SneakyThrows
    private static Boolean bindPort(String host, int port) throws Exception {
        boolean flag=false;
        try {
            Socket s = new Socket();
            s.bind(new InetSocketAddress(host, port));

            s.close();
            flag=true;
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();

        } finally{
            return flag;
        }
    }
}
